<template>
  <view>
    <!-- <cover-view> -->
    <div class="cont" id="container">
      <!-- <map class="my-map" name="" ></map> -->
      <view class="search">
        <input class="uni-input" style="" v-model="getAddress"/>
        <view class="btn" @click="searchBtn">搜索</view>
      </view>
      <view class="sure">
        <view class="text1">
          {{sureAddress}}
        </view>
        <view class="sure-btn" @click="makeSure">确认定位</view>
      </view>
    </div>
    <!-- </cover-view> -->
  </view>
</template>
<!-- <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=4e64f505a6f39e4a875b3c14961e7169"></script> --> 
<script>
let auto;
let placeSearch;
let _self;
let map;
let inputDom;
export default {
  data () {
    return {
      area: '', //省市区
      getAddress: '', // 当前的地址
      longitude: '', // 经度
      latitude: '', // 维度
      sureAddress: null,
      isFocus: false,
      lock: 1,
      fixedCity: '',
      regin: '',
      st: '' // 1：修改门店信息 0：新增门店信息
    }
  },
  onUnload: function() {
    // 监听页面卸载
    map.destroy(); //地图销毁
  },
  onLoad:function(option) {
    this.st = option.st;
    this.isFocus = true;
    this.area = option.area;
    this.regin = option.regin;
    this.getAddress = option.detail;
  },
  mounted() {
    _self = this;
    // 动态给input设置ID
    inputDom = document.getElementsByClassName("uni-input-input")[0];
    inputDom.id = 'searchInpt';
    // 引入高德地图
    var url = 'https://webapi.amap.com/maps?v=1.4.15&key=42f98d79c8315210186ad2e405eef0ea&callback=onLoad';
    var jsapi = document.createElement('script');
    jsapi.charset = 'utf-8';
    jsapi.src = url;
    document.head.appendChild(jsapi);
    window.onLoad  = function() {
      map = new AMap.Map('container');
      _self.drawMap()
    }
  },
  methods: {
    drawMap () {
      // 点击地图获取经纬度
      map.on('click',(e) => {
        //获取经纬度
        let lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()];
        this.getMapGeocoder(lnglatXY) // 获取坐标和地址
        this.longitude = e.lnglat.getLng();
        this.latitude = e.lnglat.getLat();
        let marker = new AMap.Marker({ // 点击地图定点
          position: [e.lnglat.getLng(), e.lnglat.getLat()],
          offset: new AMap.Pixel(-13, -30)
        });
        marker.setMap(map);
      });
      AMap.plugin('AMap.PlaceSearch', function() {
        placeSearch = new AMap.PlaceSearch({
          map: map,
          citylimit: true, //是否强制限制在设置的城市内搜索
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });  //构造地点查询类
        AMap.event.addListener(placeSearch, "markerClick",(e) => {
          _self.getAddress = e.data.address;
          _self.sureAddress = e.data.address;
          _self.longitude = e.data.location.lng;
          _self.latitude = e.data.location.lat;
        });
      })
      AMap.plugin('AMap.Autocomplete',function(){ //异步加载插件
        let autoOptions = {
          input: 'searchInpt', // 绑定input的id
          city: _self.area, // 设置限定的城市
          citylimit: true
        }
        auto = new AMap.Autocomplete(autoOptions);
        placeSearch.search(_self.regin + _self.getAddress);  //关键字查询查询
        AMap.event.addListener(auto, "select", function(e) { //注册监听，当选中某条记录时会触发
          placeSearch.search(_self.regin + e.poi.name);  //关键字查询查询
          // _self.searchBtn();
          if (e.poi.district == _self.regin) {
            _self.longitude = e.poi.location.lng;
            _self.latitude = e.poi.location.lat;
            _self.getAddress = e.poi.name;
            _self.sureAddress = e.poi.district + e.poi.name;
          } else {
            _self.longitude = '';
            _self.latitude = '';
            _self.getAddress = '';
            _self.sureAddress = '';
            uni.showToast({
              title: '选址不在' + `${_self.regin}` + '内！',
              icon: 'none'
            });
          }
        }); 
      });
    },
    getMapGeocoder (lnglatXY) {
      AMap.plugin('AMap.Geocoder',() => {
        let geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: 'all'
        });
        geocoder.getAddress(lnglatXY,(status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            let name = result.regeocode.addressComponent.province + result.regeocode.addressComponent.district;
            if (name != this.regin) {
              uni.showToast({
                title: '选址不在' + `${this.regin}` + '内！',
                icon: 'none'
              });
              this.getAddress = '';
              this.sureAddress = '';
            } else {
              let address = result.regeocode.addressComponent.township + result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber;
              this.getAddress = address; //逆地理
              this.sureAddress = result.regeocode.formattedAddress;
            }   
          }
        });
      });
    },
    searchBtn() {
      if (!this.getAddress) {
        uni.showToast({
          title: '请输入地址',
          icon: 'none'
        });
      }
      let gropAddress = this.regin + this.getAddress
      auto.search(gropAddress, function (e, result) {
        placeSearch.search(gropAddress);  //关键字查询查询
        if (result && JSON.stringify(result) == "{}") {
          _self.longitude = '';
          _self.latitude = '';
          _self.sureAddress = '';
          _self.getAddress = ''
          uni.showToast({
            title: '此区域内找不到该地址！',
            icon: 'none'
          });
        }
        if (e == 'complete' && result.type) {
          _self.longitude = e.poi.location.lng;
          _self.latitude = e.poi.location.lat;
          _self.sureAddress = e.poi.district + e.poi.name;
        }
      })
    },
    makeSure() {
      if (!this.longitude && !this.latitude && !this.sureAddress) {
        uni.showToast({
          title: '请先定位！',
          icon: 'none'
        });
        return false
      }
      uni.getStorage({
        key: 'saveStoreInfo',
        success: (res) => {
          let newDatas = res.data;
          newDatas.formInfo['latitude'] = this.latitude;
          newDatas.formInfo['longitude'] = this.longitude;
          newDatas.formInfo['shopAddress'] = this.getAddress;
          newDatas.newAddress = this.sureAddress;
          uni.setStorage({
            key: 'saveStoreInfo',
            data: newDatas,
            success: () => {
              if (this.st == 1) {
                uni.redirectTo({
                  url: '/pages/storeManage/index?status=1'
                });
              } else {
                uni.redirectTo({
                  url: '/pages/storeManage/index'
                });
              }
            }
          })
        }
      });
    }
  }
}
</script>
<style scoped lang="scss">
  .cont {
    width: 100%;
    height: 100vh;
    position: relative;
    .my-map {
      width: 100%;
      height: 100%;
    }
    .search {
      z-index: 8;
      width: 80%;
      position: absolute;
      top: 30rpx;
      left: 10%;
      border: 1px solid #434343;
      border-radius: 16rpx;
      background-color: #FFFFFF;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      position: relative;
      .uni-input {
        width: 70%;
        height: 60rpx;
        font-size: 24rpx;
        text-indent: 10rpx;
      }
      .btn {
        width: 30%;
        height: 60rpx;
        background-color: #434343;
        font-size: 24rpx;
        color: #F6DA99;
        text-align: center;
        line-height: 60rpx;
      }
    }
    .sure {
      z-index: 8;
      width: 100%;
      padding: 20rpx 0 64rpx;
      position: absolute;
      bottom: 0;
      background-color: #FFFFFF;
      font-size: 28rpx;
      .text1 {
        text-align: center;
        padding-left: 20rpx;
        padding-right: 20rpx;
        white-space: inherit;
      }
      .sure-btn {
        width: 80%;
        height: 60rpx;
        background-color: #434343;
        color: #F6DA99;
        text-align: center;
        line-height: 60rpx;
        border-radius: 16rpx;
        margin: 30rpx auto 0;
      }
    }
  }
</style>